<?php
namespace frontend\modules\Api\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\base\DynamicModel;
use common\services\TallyStockWarehouseService;

/**
 * Class StockWarehouseController
 *
 * @package frontend\modules\Api\controllers
 * @desc 库存 仓库 管理
 */
class StockWarehouseController extends ApiController
{
    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }

    /**
     * 仓库列表
     * @throws
     */
    public function actionLists()
    {
        $condition = Yii::$app->request->get(); // keywords 等参数
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $list = TallyStockWarehouseService::getList($tallyId,$condition);
        return self::successResponse($list);
    }

    /**
     * 获取顶多100条初始数据 不带分页 精简返回
     * @throws \yii\base\ExitException
     */
    public function actionAll()
    {
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $list = TallyStockWarehouseService::getAll($tallyId);
        return self::successResponse($list);
    }

    /**
     * 获取顶多100条初始数据 不带分页 精简返回
     * @throws \yii\base\ExitException
     */
    public function actionProductAll()
    {
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $houseId = Yii::$app->getRequest()->get('house_id');
        if(!$houseId){
            return self::failureResponse(500,'仓库Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $list = TallyStockWarehouseService::getProductAll($tallyId,$houseId);
        return self::successResponse($list);
    }

    /**
     * 某仓库下的产品关键词搜索
     * @throws \yii\base\ExitException
     */
    public function actionProductSearch()
    {
        $condition = Yii::$app->request->get(); // keywords 等参数
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $houseId = Yii::$app->getRequest()->get('house_id');
        if(!$houseId){
            return self::failureResponse(500,'仓库Id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $list = TallyStockWarehouseService::getProductSearch($tallyId,$houseId,$condition);
        return self::successResponse($list);
    }

    /**
     * 增加仓库
     * @throws
     */
    public function actionAdd()
    {
        $form = DynamicModel::validateData([
            'tally_id' => Yii::$app->getRequest()->post('tally_id'),
            'title' => Yii::$app->getRequest()->post('title'),
            'uid'   => $this->_user['id'],
        ],[
            [['tally_id','title'], 'required'],
            ['title', 'filter', 'filter' => 'trim'],
            ['title', 'string','min'=> 1,'max'=> 60],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }

        // 检查用户操作权限
        $this->checkRolePermission($this->_user['id'],$form->tally_id,'read');

        $result = TallyStockWarehouseService::create(ArrayHelper::toArray($form));
        if($result){
            return self::successResponse(['id'=>$result]);
        }else{
            return self::failureResponse(500,'新增失败.'.TallyStockWarehouseService::getError());
        }
    }

    /**
     * 编辑仓库
     * @throws
     */
    public function actionEdit()
    {
        $form = DynamicModel::validateData([
            'id'    => Yii::$app->getRequest()->post('id'),
            'tally_id' => Yii::$app->getRequest()->post('tally_id'),
            'title' => Yii::$app->getRequest()->post('title'),
        ],[
            [['title','id','tally_id'], 'required'],
            ['title', 'filter', 'filter' => 'trim'],
            ['title', 'string','min'=> 1,'max'=> 60],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }

        // 检查用户操作权限
        $this->checkRolePermission($this->_user['id'],$form->tally_id,'read');

        $result = TallyStockWarehouseService::update([
            'id'    => $form->id,
            'tally_id'   => $form->tally_id,
        ],ArrayHelper::toArray($form));
        if($result){
            return self::successResponse();
        }else{
            return self::failureResponse(500,'更新失败.'.TallyStockWarehouseService::getError());
        }
    }

    /**
     * 删除仓库
     * @throws
     */
    public function actionDel()
    {
        $id = Yii::$app->getRequest()->post('id');
        if(!$id){
            return self::failureResponse(500,'仓库Id不能为空');
        }
        $tallyId = Yii::$app->getRequest()->post('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本ID不能为空');
        }

        // 检查对账本的操作权限
        $this->checkRolePermission($this->_user['id'],$tallyId,'write');

        $result = TallyStockWarehouseService::delete([
            'id'    => $id,
            'tally_id' => $tallyId,
        ]);

        if($result){
            return self::successResponse();
        }else{
            return self::failureResponse(500,'删除失败.'.TallyStockWarehouseService::getError());
        }
    }
}
